package com.jeomo.masterdata.provider.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeomo.base.provider.controller.BaseController;
import com.jeomo.common.core.dto.ITree;
import com.jeomo.common.core.result.CommonResult;
import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.common.core.util.TreeUtil;
import com.jeomo.masterdata.provider.request.CreateGoodsTypeRequest;
import com.jeomo.masterdata.provider.request.UpdateGoodsTypeRequest;
import com.jeomo.masterdata.provider.web.vo.GoodsTypeTreeVo;
import com.jeomo.masterdata.provider.web.vo.GoodsTypeVo;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.entity.GoodsType;
import com.jeomo.masterdata.starter.exception.IntegrityConstraintViolationException;
import com.jeomo.masterdata.starter.service.IGoodsTypeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * <h3>jeomo</h3>
 * <p>品类controller</p>
 *
 * @author : 崔贺
 * @date : 2020-08-28 13:56
 **/
@RequestMapping("/masterData/goodsType")
@RestController
public class GoodsTypeController extends BaseController {

    @Resource
    private IGoodsTypeService goodsTypeService;


    @PostMapping
    @ApiOperation("创建品类")
    public CommonResult<String> create(@RequestBody CreateGoodsTypeRequest createGoodsTypeRequest) {
        try {
            GoodsType goodsType = BeanCopyUtil.copyProperties(createGoodsTypeRequest, GoodsType.class);
            List<String> parentCode = createGoodsTypeRequest.getParentCode();
            String nodeType = createGoodsTypeRequest.getNodeType();
            if (nodeType == null || nodeType.isEmpty()) {
                return CommonResult.failure("未选择节点类型");
            }
            if (parentCode == null || parentCode.size() == 0) {
                if (nodeType.equals("2")) {
                    //说明此节点类型为分组,且为根节点
                    goodsType.setParentCode("0");
                } else {
                    return CommonResult.failure("根节点类型必须是分组");
                }
            } else {
                goodsType.setParentCode(parentCode.get(parentCode.size() - 1));
            }
            goodsTypeService.create(goodsType);
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                throw new IntegrityConstraintViolationException();
            } else {
                e.printStackTrace();
                return CommonResult.failure("新增失败");
            }
        }
        return CommonResult.success("新增成功");

    }

    @DeleteMapping("/{code}")
    @ApiOperation("删除品类")
    public CommonResult<String> remove(@PathVariable("code") String code) {
        StringBuilder name = new StringBuilder();
        List<Goods> goods = goodsTypeService.removeGoodsTypeNodes(code);
        if (goods.isEmpty()) {
            return CommonResult.success("成功");
        } else {
            for (Goods pojo : goods) {
                String goodsName = pojo.getName();
                name.append(goodsName).append(",");
            }
            return CommonResult.failure("失败!关联商品名称为：" + name);
        }
    }

    @PutMapping
    @ApiOperation("修改品类")
    public CommonResult<String> update(@RequestBody UpdateGoodsTypeRequest updateGoodsTypeRequest) {
        try {
            GoodsType goodsType = BeanCopyUtil.copyProperties(updateGoodsTypeRequest, GoodsType.class);
            goodsTypeService.updateById(goodsType);
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                throw new IntegrityConstraintViolationException();
            } else {
                e.printStackTrace();
                return CommonResult.failure("修改失败");
            }
        }
        return CommonResult.success("修改成功");
    }


    @GetMapping("/{goodsTypeCode}")
    @ApiOperation("根据品类号查询品类实体")
    public CommonResult<GoodsTypeVo> queryByCode(@PathVariable("goodsTypeCode") String goodsTypeCode) {
        GoodsType goodsType = goodsTypeService.getById(goodsTypeCode);
        return CommonResult.success(BeanCopyUtil.copyProperties(goodsType, GoodsTypeVo.class));
    }

    @GetMapping("/tree")
    @ApiOperation("获取所有品类的组")
    public CommonResult<List<ITree>> tree() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
        wrapper.eq("start_flag", true);
        wrapper.eq("node_type", "2");
        List<GoodsType> list = goodsTypeService.list(wrapper);
        List<ITree> nodes = BeanCopyUtil.copyListProperties(list, GoodsTypeTreeVo::new);
        return CommonResult.success(TreeUtil.buildTree(nodes));
    }

    @GetMapping("/allTree")
    @ApiOperation("获取所有品类(全部)")
    public CommonResult<List<ITree>> allTree() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        List<GoodsType> list = goodsTypeService.list();
        List<ITree> nodes = BeanCopyUtil.copyListProperties(list, GoodsTypeTreeVo::new);
        return CommonResult.success(TreeUtil.buildTree(nodes));
    }


    @GetMapping("/all")
    @ApiOperation("获取所有品类节点")
    public CommonResult<List<GoodsTypeVo>> all() {
        QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
        wrapper.eq("start_flag", true);
        wrapper.eq("node_type", "1");
        List<GoodsType> goodsTypes = goodsTypeService.list(wrapper);
        return CommonResult.success(BeanCopyUtil.copyListProperties(goodsTypes, GoodsTypeVo::new));
    }
}
